<?php
namespace app\admin\model;

use app\lib\exception\ParameterException;
use think\Model;
use traits\model\SoftDelete;

class Product extends Base
{
    use SoftDelete;
    public function shop(){
        return $this->hasOne("Shop","id","uid")->bind("name,type");
    }
    /**
     * 生成商品编号
     * @author aurora
     * @date 2018-11-09
     * @param string $char 订单编号所带的大写字母
     * @param int $length 订单编号后字符串长度
     * @return int|string
     */
    public function createProductCode($char = "", $length = 4) {
        do {
            $product_code = $char . date('YmdHis');
            for ($i = 0; $i < $length; $i++) {
                $product_code .= rand(0, 9);
            }
            $count = $this->getCount(['product_code' => $product_code]);   //保证生成的订单编号不会重复
        } while ($count>0);

        return $product_code;
    }

    /**
     * 商品-分类 操作
     * @param $product_id
     * @param array $data
     * @return array|string
     * @throws \Exception
     */
    public function productCategory($product_id, $data = []) {
        $mall_product_category_model = new ProductCategoryRelation();
        $res = $mall_product_category_model->where('product_id','eq', $product_id)->delete();
        if ($res === false) {
            return ajax_api();
        }
        $insert_array = [];
        foreach ($data['category_id'] as $key => $value) {
            $insert_array[] = [
                'product_id' => $product_id,
                'category_id' => $value
            ];
        }
        $res = $mall_product_category_model->insertAll($insert_array);
        if ($res === false) {
            return false;
        }
        return true;
    }

    /**
     * 商品-分组
     * @param $product_id
     * @param array $data
     * @return array|string
     * @throws \Exception
     */
    public function productGroup($product_id, $data = []) {
        $mall_product_category_model = new ProductGroupRelation();
        $res = $mall_product_category_model->where('product_id','eq', $product_id)->delete();
        if ($res === false) {
            return ajax_api();
        }
        $insert_array = [];
        if (array_key_exists('group_id', $data)) {
            foreach ($data['group_id'] as $key => $value) {
                $insert_array[] = ['product_id' => $product_id,'group_id' => $value];
            }
            $res = $mall_product_category_model->insertAll($insert_array);
            if ($res === false) { return false; }
        }
        return true;
    }

    /**
     * 商品-分组
     * @param $product_id
     * @param array $data
     * @return array|string
     */
    public function productPrice($product_id, $data = [],$uid) {
        $product_price_model = new ProductPrice();
        $where_price = [['product_id','eq',$product_id],['type','in',[1,2]]];
        $res = $product_price_model->where($where_price)->setField("delete_time",time());
        if ($res === false) { return ajax_api(); }

        $insert_array = [];
        foreach ($data as $key => $value) {
            if($value['type'] != 1 && $value['type'] !=2){
                continue;
            }
            $insert_array[] = [
                'uid'  => $uid,
                'type' => $value['type'],
                'product_id' => $product_id,
                'price' =>$value['price'],
                'min_number'=>$value['min_number'],
                'max_number'=>$value['max_number'],
                'create_time'=>time()
            ];
        }
        $res = $product_price_model->insertAll($insert_array);
        if ($res === false) {
            return  false;
        }
        return true;
    }

    /**
     * 商品规格操作
     * @param $product_id
     * @param array $data
     * @return array|string
     */
    public function productSpec($product_id, $data = []) {
        $product_spec_model = new ProductSpec();
        $product_spec_item_model = new ProductSpecItem();
        $product_sku_model = new ProductSku();
        //清空数据
        $where = [['uid' ,'eq', $data['uid']], ['product_id' ,'eq', $product_id]];
        $product_spec_model->where($where)->setField("delete_time",time());
        $product_spec_item_model->where($where)->setField("delete_time",time());
        $product_sku_model->where($where)->setField("delete_time",time());
        //保存规格名
        $spec_data = [];
        $spec_item_data = [];
        if (!array_key_exists('spec_id_list', $data)) {
            return  ['code'=>0,"msg"=>'属性集没有传'];
        }
        foreach ($data['spec_id_list'] as $key => $value) {
            $spec_data[] = [
                'uid' => $data['uid'],
                'product_id' => $product_id,
                'spec_id' => $value['spec_id'],
                'spec_title' => $value['spec_title'],
                'create_time' => time(),
            ];
            if (!array_key_exists('spec_item_list' , $data)) {
                return  ['code'=>0,"msg"=>'属性值没有传'];
            }
            foreach ($data['spec_item_list'] as $k => $v) {
                if($v['spec_id']==$value['spec_id']){
                    $spec_item_data[] = [
                        'uid' => $data['uid'],
                        'product_id' => $product_id,
                        'spec_id' => $value['spec_id'],
                        'spec_item_id' => $v['spec_item_id'],
                        'spec_item_value' => $v['spec_item_value'],
                        'create_time' => time(),
                    ];
                }
            }
        }
        $res = $product_spec_model->insertAll($spec_data);
        if ($res === false) {
            return  ['code'=>0,"msg"=>'商品属性集添加失败'];
        }
        //保存规格值
        $res = $product_spec_item_model->insertAll($spec_item_data);
        if ($res === false) {
            return  ['code'=>0,"msg"=>'商品属性值添加失败'];
        }
        //保存SKU
        $sku_data = [];
        foreach ($data['sku_list'] as $key => $value) {
            if(!isset($value['sku_name'])||$value['sku_name']==""){
                return  ['code'=>0,"msg"=>'属性名称不能为空'];
            }
            $sku_data = [
                'uid' => $data['uid'],
                'product_id' => $product_id,
                'sku' => $value['sku'],
                'stock' =>isset($value['stock'])?$value['stock'] : 0,
                'sku_name' =>isset($value['sku_name'])?$value['sku_name']:"",
                'sku_code'=>$this->createSkuCode("SKU"),
                'create_time' => time()
            ];
            $id = $product_sku_model->insert($sku_data,false,true);
            if (!($id > 0)) {
                return  ['code'=>0,"msg"=>'商品规格添加失败'];
            }

            $product_price = [];
            foreach ($value['product_price'] as $key1 => $value1){
                if($value1['max_number'] < $value1['min_number']){
                    return  ['code'=>0,"msg"=>'起批数量不正确'];
                }
                $price['type'] = $value1['type'];
                $price['min_number'] = $value1['min_number'];
                $price['max_number'] = $value1['max_number'];
                array_push($product_price,$price);
            }
            $res = $this->productPrice($product_id, $id, $product_price);
            if (!($res > 0)) {
                return  ['code'=>0,"msg"=>'商品价格添加失败'];
            }
        }

        //规格添加成功 之后  如果商家是 线上 就添加 到虚拟仓库里面
        $type = (new Shop())->findOne([['id','eq',$data['uid']]],"type");
        if($type ==1){
            foreach ($sku_data as $key=>$value){
                $sku_data[$key]['actual_stock'] = $value['stock'];
            }
            $res=warehouseChangeStock(3,1,$sku_data);
            if($res['code']!=1){
                return $res;
            }
        }
        return  ['code'=>1,"msg"=>'商品添加成功'];
    }

    /**
     * 创建sku编码
     * @param string $char
     * @param int $length
     * @return string
     */
    public function createSkuCode($char = "", $length = 10){
        do {
            $sku_code = $char . date('YmdHis');
            for ($i = 0; $i < $length; $i++) {
                $sku_code .= rand(0, 9);
            }
            $count = (new ProductSku())->getCount(['sku_code' => $sku_code]);   //保证生成的sku编号不会重复
        } while ($count>0);
        return $sku_code;
    }

    /**
     * 根据商品分组名称返回对应ID
     * @param $name
     * @param $uid
     * @return int|mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGroupIdByName($name,$uid){
        $shopGroup = new ShopGroup();
        $where["uid"] = $uid;
        $where["group_name"] = $name;
        $model = $shopGroup->where($where)->find();
        if($model != null){
            return $model["id"];
        }else{
            $newModel = array(
                "uid"=>$uid,
                "group_name"=>$name,
                "sort"=>0,
                "create_time"=>time(),
                "update_time"=>time(),
            );
            return $shopGroup->insert($newModel,false,true);
        }
    }
}